<?php

namespace App\Tyt\Manager\Storage;


use App\Models\FileTransaction;
use App\Models\Qiniu;
use App\Tyt\Service\Storage\StorageInterface;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class StorageManager implements StorageInterface
{

    protected $access_key;

    protected $secret_key;

    protected $bucket;

    protected $params;

    protected $result;

    protected $error;

    /**
     * 初始化配置信息
     * @param Qiniu $qiniu
     * @return StorageInterface
     */
    public function init(Qiniu $qiniu): StorageInterface
    {
        $this->access_key = $qiniu->access_key;
        $this->secret_key = $qiniu->secret_key;
        $this->bucket = $qiniu->bucket;
        return $this;
    }

    /**
     * 发送文件
     */
    public function send(): StorageInterface
    {
        $uploadMgr = new UploadManager();
        list($this->result, $this->error) = $uploadMgr->putFile(
            $this->token(),
            $this->params['name'],
            $this->params['path']
        );
        return $this;
    }

    /**
     * 验证是否成功
     */
    public function isSuccess(): bool
    {
        return (bool)is_null($this->error);
    }

    /**
     * 获取返回数据
     */
    public function getData()
    {
        return $this->result ?? $this->error;
    }

    /**
     * 获取token
     */
    private function token(): string
    {
        $auth = new Auth($this->access_key, $this->secret_key);
        $token = $auth->uploadToken($this->bucket);
        return $token;
    }

    /**
     * 设置参数
     * @param array $attributes
     * @return StorageInterface
     */
    public function setParams(array $attributes): StorageInterface
    {
        $this->params = $attributes ?? [];
        return $this;
    }

    /**
     * 设置文件名
     * @param FileTransaction $transaction
     * @return string
     */
    public function setName(FileTransaction $transaction): string
    {
        return str_random(10) . $transaction->name;
    }
}